//
//  NearbyWeiboViewController.m
//  HCWeibo
//
//  Created by gj on 15/12/19.
//  Copyright © 2015年 www.iphonetrain.com 无限互联. All rights reserved.
//

#import "NearbyWeiboViewController.h"
#import "WeiboAnnotation.h"

/**
 *  标注视图 实现步骤
    1、定义（遵循 MKAnnotation）annotation类,本质是model类
    2、创建annotation对象，把该对象添加到地图上
    3、实现mapView的协议方法
    4、自定义标注视图类 annotationView
 
 */



@interface NearbyWeiboViewController ()

@end

@implementation NearbyWeiboViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"附近微博";
    [self _createMapView];
    
    
    //测试：创建两个标注model对象，然后添加到mapView中
//    WeiboAnnotation *annotation1 = [[WeiboAnnotation alloc] init];
//    
//    CLLocationCoordinate2D coordinate1 = {30.2242,120.2019};
//    [annotation1 setCoordinate:coordinate1];
//    annotation1.title = @"大家好";
//    [_mapView addAnnotation:annotation1];
//    
//    
//    WeiboAnnotation *annotation2 = [[WeiboAnnotation alloc] init];
//    CLLocationCoordinate2D coordinate2 = {30.2142,120.2019};
//    annotation2.title = @"好";
//    [annotation2 setCoordinate:coordinate2];
//    
//    [_mapView addAnnotation:annotation2];
    
    
    
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//地图显示类型

//MKMapTypeStandard = 0,
//MKMapTypeSatellite,
//MKMapTypeHybrid,
//MKMapTypeSatelliteFlyover
//MKMapTypeHybridFlyover

//创建地图视图
- (void)_createMapView{
    
    _locationManager = [[CLLocationManager alloc] init];
    
    if (ios8) {
        [_locationManager requestWhenInUseAuthorization];
    }
    

    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    //显示用户位置
    _mapView.showsUserLocation = YES;
    //地图类型
    _mapView.mapType = MKMapTypeStandard;
    //设置代理
    _mapView.delegate = self;
    //用户跟踪模式
   // _mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    [self.view addSubview:_mapView];

}

//网络获取附近的微博
- (void)_loadNearbyWeiboWithLong:(NSString *)longStr lat:(NSString *)latStr{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:longStr forKey:@"long"];
    [params setObject:latStr forKey:@"lat"];
    [params setObject:@50 forKey:@"count"];
    
    
    [NetworkService requestDataWithURL:nearby_timeline HTTPMethod:@"GET" params:params completionHandle:^(id result, NSURLResponse *response, NSError *error) {
        
        NSArray *statuses = [result objectForKey:@"statuses"];
        NSMutableArray *annotationArray = [[NSMutableArray alloc] init];
        
        
        for (NSDictionary *dic in statuses) {
            //获取微博model
            WeiboModel *weiboModel = [[WeiboModel alloc] initWithDataDic:dic];
            //如果没有地理位置信息的微博则舍弃
            if (![weiboModel.geo isEqual:[NSNull null]]) {
                //创建annotaion
                WeiboAnnotation *annotation = [[WeiboAnnotation alloc] init];
                annotation.weiboModel = weiboModel;
                [annotationArray addObject:annotation];
            }
            
        }
        
        //把annotation添加到mapView中
        NSLog(@"%li条微博",annotationArray.count);
        [_mapView addAnnotations:annotationArray];
        
        
    }];
    
    
}


#pragma mark - mapView 代理

//当标注视图被添加到mapView的时候被调用
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
    
    for (int i = 0; i<views.count; i++) {
        WeiboAnnotationView *view = (WeiboAnnotationView*)views[i];
        
        if (![view isKindOfClass:[WeiboAnnotationView class]]) {
            continue;
        }
        
        view.transform = CGAffineTransformMakeScale(0.5, 0.5);
        view.alpha = 0;
        
        [UIView animateWithDuration:1 animations:^{
            //设置动画延迟时间
            [UIView setAnimationDelay:i*0.1];
            view.transform = CGAffineTransformMakeScale(1.3, 1.3);
            view.alpha = 1;

        } completion:^(BOOL finished) {
            if (finished) {
                [UIView animateWithDuration:0.3 animations:^{
                    view.transform = CGAffineTransformMakeScale(1, 1);
                }];
            }
    
        }];
        
        
    }

    
}

//当标注视图被选中
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    
    DetailViewController *detailVc = [[DetailViewController alloc] init];
    
    //拿到标注数据model
    WeiboAnnotation *annotation = view.annotation;
    
    WeiboModel *weiboModel = annotation.weiboModel;
    WeiboViewLayoutFrame *layoutFrame = [[WeiboViewLayoutFrame alloc] init];
    layoutFrame.weiboModel = weiboModel;
    detailVc.layoutFrame = layoutFrame;
    
    [self.navigationController pushViewController:detailVc animated:YES];

    
    
}


- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView {
    
    NSLog(@"START");

}
- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView{
    NSLog(@"stop");
}

//位置更新
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"UPDATE");
    
    //01 获取经纬度
    CLLocation *location = userLocation.location;
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    NSLog(@"longitude = %lf,latitude = %lf",coordinate.longitude,coordinate.latitude);
    
    //02 网络通讯获取附近的微博
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",coordinate.longitude];
    
    NSString *latitudeStr = [NSString stringWithFormat:@"%lf",coordinate.latitude];
    [self _loadNearbyWeiboWithLong:longitudeStr lat:latitudeStr];
    
    
    //03 设置地图显示区域
    //数字越小，显示区域越精确
    MKCoordinateSpan  span = {0.1,0.1};
    //显示区域中心点
    CLLocationCoordinate2D center = coordinate;
    MKCoordinateRegion region = {center,span};//中心坐标，参数
    //设置地图显示区域
    [mapView setRegion:region];
}


//返回annotationView
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    if ([annotation isKindOfClass:[WeiboAnnotation class]]) {
    
        WeiboAnnotationView *annotationView = (WeiboAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"view"];
        
        if (annotationView == nil) {
//            annotationView = [[WeiboAnnotationView alloc] initWithFrame:CGRectZero];
            
            annotationView = [[WeiboAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"view"];
            
        }
        
        annotationView.annotation = annotation;
        return annotationView;
        
        
    }
    
    return nil;
    

}


//// 一、学习知识点：为标注model提供视图view
//- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
//    
//    //如果是用户定位信息，则用默认的标注视图
//    if ([annotation isKindOfClass:[MKUserLocation class]]) {
//        return nil;
//    }
//    
//    //如果是weiboAnnotation则返回大头针视图
//    if ([annotation isKindOfClass:[WeiboAnnotation class]]) {
//        // MKAnnotationView 子类
//        MKPinAnnotationView *pinView = (MKPinAnnotationView*) [mapView dequeueReusableAnnotationViewWithIdentifier:@"view"];
//        
//        
//        if (pinView == nil) {
//            
//            pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"view"];
//            
//            //颜色
//            pinView.pinTintColor = [UIColor greenColor];
//            //从天而降动画效果
//            pinView.animatesDrop = YES;
//            
//            //显示标题
//            pinView.canShowCallout = YES;
//            
//            //右侧辅助视图
//            pinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//            
//        
//        }
//        
//        return pinView;
//        
//    }
//    
// 
//    return  nil;
//}





@end
